package main

import (
	"encoding/json"
	"fmt"
	"gopkg.in/yaml.v2"
	"log"
	"os"
	"reflect"
	"strings"
)

type Config struct {
	Edge Edge `yaml:"EDGE"`
}

type Edge struct {
	Hostname      string `yaml:"hostname"`
	Mode          string `yaml:"mode"`
	ClusterRole   string `yaml:"clusterRole"`
	MgmtInterface string `yaml:"mgmtInterface"`
	CtlIpaddress  string `yaml:"ctlIpaddress"`
	MgmtIpaddress string `yaml:"mgmtIpaddress"`
	Vip           string `yaml:"vip"`
	VipInterface  string `yaml:"vipInterface"`
	ManageIP      string `yaml:"manageIP"`
	Token         string `yaml:"token"`
}

func ReadYamlConfig(path string)  (*Config,error){
	conf := &Config{}
	if f, err := os.Open(path); err != nil {
		return nil,err
	} else {
		yaml.NewDecoder(f).Decode(conf)
	}
	return  conf,nil
}

func getTag(member string) string {
	//获取标签
	n := reflect.TypeOf(Edge{})
	//打印字段MTU的标签
	str, _ := n.FieldByName(member)
	//fmt.Println(str.Tag)

	return strings.Split(string(str.Tag), "\"")[1]
}


func ForeachStruct(obj interface{}) {
	t := reflect.TypeOf(obj) // 注意，obj不能为指针类型，否则会报：panic recovered: reflect: NumField of non-struct type
	v := reflect.ValueOf(obj)
	for k := 0; k < t.NumField(); k++ {
		fmt.Printf("%s -- %v \n", t.Field(k).Tag, v.Field(k).Interface())
	}
}

func TranStructToEnv(obj interface{}) {
	t := reflect.TypeOf(obj) // 注意，obj不能为指针类型，否则会报：panic recovered: reflect: NumField of non-struct type
	v := reflect.ValueOf(obj)
	env := []string{}
	for k := 0; k < t.NumField(); k++ {
		tag := strings.Split(string(t.Field(k).Tag), "\"")[1]
		envT := fmt.Sprintf("%s_%s=%v", strings.ToUpper(t.Name()), tag, v.Field(k).Interface())
		env = append(env, envT)
	}
	fmt.Println(env)
}

func main() {
	//解析文件
	conf,err := ReadYamlConfig("node.yaml")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(conf.Edge.Hostname)

	byts,err := json.Marshal(conf)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(string(byts))

	tag := getTag("Hostname")
	fmt.Println(tag)


	//遍历结构体
	//ForeachStruct(conf.Edge)
	TranStructToEnv(conf.Edge)

}
